package com.mengwen.backstage.api.accesstoken;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mengwen.backstage.pojo.AccessToken;
import net.sf.json.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;
import static com.mengwen.backstage.util.WeixinUtil.httpRequest;

/**
 * 获取最新的accesstoken
 */
public class GetLastAcceccToken {

    // 获取access_token的接口地址（GET） 限200（次/天）
    private final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 获取最新的access_token
     * @param redisTemplate
     * @return
     * @throws Exception
     */
    public static AccessToken getAccessToken(RedisTemplate redisTemplate) throws Exception {
        AccessToken accessToken = null;
        String redisAccessTokenString = (String)redisTemplate.opsForValue().get("my:accesstoken:string");
        if ("".equals(redisAccessTokenString) || redisAccessTokenString == null) {
            String requestUrl = access_token_url.replace("APPID", AppIdAndSecret.appId).replace("APPSECRET", AppIdAndSecret.appSecret);
            JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
            if (null == jsonObject)
            {
                throw new Exception("获取token失败");
            }

            System.out.println("从微信服务器获取凭证："+jsonObject.toString());
            accessToken = new AccessToken();
            accessToken.setToken(jsonObject.getString("access_token"));
            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            redisTemplate.opsForValue().set("my:accesstoken:string",jsonObject.getString("access_token"));
            redisTemplate.expire("my:accesstoken:string",10, TimeUnit.MINUTES);
        }else {
            System.out.println("从redis中获取凭证：");
            System.out.println( redisAccessTokenString);
            System.out.println("========================================");
            accessToken = new AccessToken();
            accessToken.setToken( redisAccessTokenString);
            accessToken.setExpiresIn(7200);
        }

        return accessToken;
    }


}
